//
//  BIProjectContext.m
//  BIUserModule
//
//  Created by 杨洋 on 2021/8/19.
//

#import "BIProjectContext.h"
#import "BISafeVC.h"
#import "BIUpdateVersionView.h"
#import "BIUpdateVersionModel.h"
#import "BIAdvertisementView.h"
#import "BIAdvertisementModel.h"

#import <BINetworkModule/BICookieManager.h>
#import <BINetworkModule/BINetworkManager.h>
#import <BINetworkModule/BIMonitorManager.h>
#import <BIUserModule/BIUserManager.h>
#import <BIUserModule/BILoginVC.h>
#import <BIToolModule/BILanguage.h>
#import <BIPushModule/BIPushManager.h>
#import <BIDebugModule/BIDebugManager.h>
#import <BIThirdModule/BIBuglyManager.h>
#import <BIThirdModule/BIQuickLoginManager.h>
#import <BIBluetoothModule/BIBluetoothManager.h>
#import <BIWebModule/BIWKWebView.h>

#import <BIToolModule/UIImage+Helper.h>
#import <BIProjectModule/BIAppDefine.h>
#import <BIToolModule/NSString+Helper.h>
#import <BIToolModule/NSObject+Helper.h>
#import <BIToolModule/NSDate+Helper.h>
#import <BIToolModule/NSMutableDictionary+Helper.h>
#import <BIToolModule/NSObject+ViewController.h>
#import <BIToolModule/NSObject+HUD.h>

#import <YYKit/YYKit.h>
#import <YYNavigation/YYNavigation.h>
#import <SDWebImage/SDWebImage.h>

@interface BIProjectContext ()

@property (nonatomic, readwrite) BITabBarVC *tabBarVC;
/// 是否支持横盘
@property (nonatomic, assign) BOOL isEnabledLandscape;

@end

@implementation BIProjectContext

#pragma mark - LifeCycle

BISingletonImplementation()

- (void)launchWithOptions:(NSDictionary *)launchOptions {
    // 最早初始化bugly管理器
    [[BIBuglyManager sharedInstance] launch];
    // 设置window，并检测是否连续崩溃
    if ([self bi_configWindow]) return;
    // 初始语言
    [[BILanguage sharedInstance] launch];
    // 初始化debug视图
    [[BIDebugManager sharedInstance] launch];
    // 初始本地管理framework和.a的第三方库，如果能引pod的，无需在这处理
    [[BIQuickLoginManager sharedInstance] launch];
    // 预加载一个webview
    [BIWKWebView prepareWebView];
    // 设置全局导航栏
    [self bi_configGlobalNavigationBar];
    // 读取本地user对象
    [[BIUserManager sharedInstance] loadUserFromLocal];
    // 初始化network管理器
    [[BINetworkManager sharedInstance] launch];
    // 初始化cookie管理器
    [[BICookieManager sharedInstance] launchWithConfig:kBIRequestKeyValueSaveHeader];
    // 初始化网络监听
    [[BIMonitorManager sharedInstance] launch];
    // 设置网络请求的全局状态码，需要重新登录
    [[BINetworkManager sharedInstance] setupGlobalStatusCode:[NSSet setWithObjects:@"1024", @"1008", @"1005", @"1002", nil] block:^(BINetworkResponse *response) {
        [self bi_refreshToken];
        // 退出
        [self logout];
        // 打开登录页
        [self openLoginVCWithSucceedBlock:nil];
    }];
    // 启动蓝牙，开始扫描
    // 写特征字典
    NSMutableDictionary *writeUUIDDic = [NSMutableDictionary dictionary];
    [writeUUIDDic safeSetObject:@"SLEBluetoothCMD" key:@"AE3B"];
    // 读特征字典
    NSMutableDictionary *readUUIDDic = [NSMutableDictionary dictionary];
    [readUUIDDic safeSetObject:@"SLEBluetoothDeviceModel" key:@"AE3C"];
    [[BIBluetoothManager sharedInstance] launchWithWriteUUIDS:writeUUIDDic readUUIDS:readUUIDDic];
    [[BIBluetoothManager sharedInstance] scanBluetoothList];
//    // 启动push推送管理器
//    [[BIPushManager sharedInstance] launchWithOptions:launchOptions];
    // 设置根视图为tabbarVC
    [self bi_configTabBarVC];
    // 处理登录态与非登录态的逻辑
    [self bi_handleLoginStatus];
}

- (void)resume {
   
}

- (void)terminate {
    
}

- (void)remoteNotificationsSucceed:(NSData *)deviceToken {
    [[BIPushManager sharedInstance] remoteNotificationsSucceed:deviceToken];
}

- (void)didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [[BIPushManager sharedInstance] didReceiveRemoteNotification:userInfo];
}

- (UIInterfaceOrientationMask)supportInterfaceOrientation {
    return self.isEnabledLandscape ? UIInterfaceOrientationMaskAllButUpsideDown : UIInterfaceOrientationMaskPortrait;
}

#pragma mark - Public Method

- (void)forceDeviceOrientation:(UIDeviceOrientation)deviceOrientation {
    if (deviceOrientation == UIDeviceOrientationPortrait) {
        self.isEnabledLandscape = NO;
    } else {
        self.isEnabledLandscape = YES;
    }
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:deviceOrientation] forKey:@"orientation"];
}

- (void)openLoginVCWithSucceedBlock:(dispatch_block_t)succeedBlock {
    [[BIQuickLoginManager sharedInstance] openQuickLogin:^(id value) {
        NSString *resultCode = value[@"resultCode"];
        if ([@"600001" isEqualToString:resultCode] ||
            [@"700002" isEqualToString:resultCode] ||
            [@"700003" isEqualToString:resultCode] ||
            [@"700006" isEqualToString:resultCode] ||
            [@"700007" isEqualToString:resultCode] ||
            [@"700008" isEqualToString:resultCode] ||
            [@"700004" isEqualToString:resultCode] ||
            [@"700009" isEqualToString:resultCode]) {
        } else if ([@"700000" isEqualToString:resultCode] ||
                   [@"700010" isEqualToString:resultCode]) {
            [[BIQuickLoginManager sharedInstance] closeQuickLogin];
        } else if ([@"700001" isEqualToString:resultCode]) {
            NSMutableDictionary *arguments = [NSMutableDictionary dictionary];
            [arguments safeSetObject:succeedBlock key:@"loginSucceedBlock"];
            [arguments safeSetObject:@(YES) key:@"isUseSystemNavigationBar"];
            [[BIRouteManager sharedInstance] openVCCMD:@"login" isPresent:NO arguments:arguments];
        } else if ([@"600000" isEqualToString:resultCode]) {
            NSString *token = [value objectForKey:@"token"];
            UIPasteboard *generalPasteboard = [UIPasteboard generalPasteboard];
            if ([token isKindOfClass:NSString.class]) {
                generalPasteboard.string = token;
            }
            [self bi_quickLogin:token];
        } else {
            // 当一键登录失败，不管是怎么失败，都关闭一键登录，打开普通登录
            [[BIQuickLoginManager sharedInstance] closeQuickLogin];
            // 当前页面栈的第一个界面
            UIViewController *currentVC = [NSObject currentVC];
            // 未打开登录模块，才能打开
            if (![currentVC.navigationController.viewControllers.firstObject isKindOfClass:[BILoginVC class]]) {
                NSMutableDictionary *arguments = [NSMutableDictionary dictionary];
                [arguments safeSetObject:succeedBlock key:@"loginSucceedBlock"];
                [arguments safeSetObject:@(NO) key:@"isUseSystemNavigationBar"];
                [[BIRouteManager sharedInstance] openVCCMD:@"login" isPresent:YES arguments:arguments];
            }
        }
    }];
}

- (void)updateUserInfo:(BIUserModel *)userInfo {
    // 更新本地的user缓存，同时user对象也会切换
    [[BIUserManager sharedInstance] saveUserObjectToLocal:userInfo];
    // 登入后，立即添加Cookie
    [[BICookieManager sharedInstance] addUserCookie];
    // 更新Bugly的用户标识符
    [[BIBuglyManager sharedInstance] setupUserIdentifier:userInfo.phone];
    // 更新推送的empid
    [[BIPushManager sharedInstance] uploadEmpID:userInfo.customerId];
}

- (void)logout {
    // 调用退出登录接口
    [self bi_requestLogout];
    // 删除本地的user缓存，同时user对象只会保留oldUserId和oldPlatformNum的值
    [[BIUserManager sharedInstance] removeUserFromLocal];
    // 移除推送的empID
    [[BIPushManager sharedInstance] uploadEmpID:@""];

    // 登出后，立即清理Cookie
    [[BICookieManager sharedInstance] clearUserCookie];
    
}

#pragma mark - Private Method

- (BOOL)bi_configWindow {
    self.appDelegate.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.appDelegate.window.backgroundColor = [UIColor whiteColor];
    // app是否出现连续crash，如果出现则显示安全界面，并结束后续初始化
    if ([BIBuglyManager isAppCrashedOnStartUpExceedTheLimit]) {
        self.appDelegate.window.rootViewController = [BISafeVC new];
        [self.appDelegate.window makeKeyAndVisible];
        return YES;
    } else {
        return NO;
    }
}

- (void)bi_configGlobalNavigationBar {
    // 如果你全局用的颜色，一级tab界面用颜色修改，如果用图片修改会因为appearance出现逻辑问题
    // 如果你全局用的图片，一级tab界面用图片修改，如果用颜色修改会因为appearance出现逻辑问题
    // 二级界面没有这个问题
    [[YYNavigationBar appearance] setNaviBgColor:[UIColor loadColorFromString:@"0xFFFFFF"]];
    [[YYNavigationItem appearance] setTextColor:[UIColor loadColorFromString:@"0x333333"]];
}

- (void)bi_configTabBarVC {
    self.tabBarVC = [BITabBarVC new];
    self.appDelegate.window.rootViewController = self.tabBarVC;
    [self.appDelegate.window makeKeyAndVisible];
}

- (void)bi_handleLoginStatus {
    if (self.user.isLogin) {
        // 更新cookie等用户信息
        [self updateUserInfo:[BIUserManager sharedInstance].user];
        // 登录态，刷新tabbarVC；如果数据与本地无差异，则保持原样
        [self.tabBarVC refreshTabBarController];
    } else {
        // 打开登录页
        [self openLoginVCWithSucceedBlock:nil];
    }
}


#pragma mark - Network

- (void)bi_requestLogout {
    NSString *path = @"ssogateway/sso-gateway/pwd/logout.do";
    BINetworkRequest *request = [[BINetworkManager sharedInstance] requestWithPath:path arguments:nil succeedBlock:nil failureBlock:nil completionBlock:nil];
    [[BINetworkManager sharedInstance] startRequest:request];
}

- (void)bi_refreshToken {
    NSMutableDictionary *arguments = [NSMutableDictionary dictionary];
    [arguments safeSetObject:self.user.refreshToken key:@"refreshToken"];

    NSString *path = @"/api/app/account/refreshToken";
    BINetworkRequest *request = [[BINetworkManager sharedInstance] requestWithPath:path arguments:arguments succeedBlock:^(BINetworkResponse *response) {
        BIUserModel *user = response.modelValue;
        self.user.refreshToken = user.refreshToken;
        self.user.accessToken = user.accessToken;
        [self updateUserInfo:self.user];
    } failureBlock:^(BINetworkResponse *response) {
        // 退出
        [self logout];
        [self openLoginVCWithSucceedBlock:nil];
    } completionBlock:nil];
    request.responseClass = [BIUserModel class];
    [[BINetworkManager sharedInstance] startRequest:request];
}

- (void)bi_queryUserInfo {
    NSString *path = @"/api/app/account/getUserInfo";
    BINetworkRequest *request = [[BINetworkManager sharedInstance] requestWithPath:path arguments:nil succeedBlock:^(BINetworkResponse *response) {
        BIUserModel *user = response.modelValue;
        user.accessToken = self.user.accessToken;
        user.refreshToken = self.user.refreshToken;
        [[BIProjectContext sharedInstance] updateUserInfo:user];
        [[BIQuickLoginManager sharedInstance] closeQuickLogin];
    } failureBlock:nil completionBlock:nil];
    request.methodType = kBINetworkGetMethodType;
    request.responseClass = [BIUserModel class];
    request.responseKeyPath = @"data";
    [[BINetworkManager sharedInstance] startRequest:request];
}

- (void)bi_quickLogin:(NSString *)token {
    NSMutableDictionary *arguments = [NSMutableDictionary dictionary];
    [arguments safeSetObject:token key:@"token"];
    NSString *path = @"/api/app/account/oneClickLogin";

    [self showActivityHUD];
    BINetworkRequest *request = [[BINetworkManager sharedInstance] requestWithPath:path arguments:arguments succeedBlock:^(BINetworkResponse *response) {
        [self hideActivityHUD];
        BIUserModel *user = response.modelValue;
        [[BIProjectContext sharedInstance] updateUserInfo:user];
        [[BICookieManager sharedInstance] setCookieName:@"token" cookieValue:user.accessToken];
        [self bi_queryUserInfo];
    } failureBlock:^(BINetworkResponse *response) {
        [self hideActivityHUD];
        [NSObject showTextHUDWithTitle:response.msg afterDelay:1.5 completionBlock:nil];
    } completionBlock:nil];
    request.responseClass = [BIUserModel class];
    request.responseKeyPath = @"data";
    [[BINetworkManager sharedInstance] startRequest:request];
}


#pragma mark - Getter

- (BIAppDelegate *)appDelegate {
    return [UIApplication sharedApplication].delegate;
}

- (BIUserModel *)user {
    return [BIUserManager sharedInstance].user;
}

@end
